/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * MeetTaskService
 * 任务信息
 * <p>
 * 修改纪录
 * 2020-08-28 版本：1.0 shenyouyi 创建。
 *
 * @version 版本：1.0
 * @author 作者：shenyouyi
 * 创建日期：2020-08-28
 */
package com.topscomm.meet.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.topscomm.meet.pojo.MeetManageEntity;
import com.topscomm.meet.service.IMeetManageService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.topscomm.base.service.IBaseCboUserExtendService;
import com.topscomm.base.service.IBaseTeamUserService;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboOrgService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.meet.MeetSystemConst;
import com.topscomm.meet.pojo.MeetTaskEntity;
import com.topscomm.meet.service.IMeetTaskService;
import com.topscomm.meet.service.ISmsWorkTasksCloseService;
import com.topscomm.meet.service.impl.auto.MeetTaskServiceAuto;
import com.topscomm.meet.vo.OAResult;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;

@Service(value = "meetTaskService")
@Scope(value = "singleton")
public class MeetTaskService extends MeetTaskServiceAuto implements IMeetTaskService {

	@Autowired
	private ICboUserService cboUserService;
	@Autowired
	private ISmsWorkTasksCloseService smsWorkTasksCloseService;
	@Autowired
	private IBaseTeamUserService baseTeamUserService;
	@Autowired
	private ICboDeptService cboDeptService;
	@Autowired
	private ICboOrgService cboOrgService;

	@Autowired
	private IBaseCboUserExtendService baseCboUserExtendService;

	@Autowired
	private IMeetManageService meetManageService;


	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-21
	 * @param: paraMap
	 * @description: 从OA中获取任务列表
	 * @modify:
	 */
	@Override
	public Page searchTaskFromOA(Map<String, Object> paraMap) {
		String qry_meetID = (String) paraMap.get("qry_meetID");
		Map<String, Object> paraOA = new HashMap<>();
		paraOA.put("sourcesys", MeetSystemConst.OATaskSourceInfo.Sourcesys);
		paraOA.put("sourcemoudule", MeetSystemConst.OATaskSourceInfo.Sourcemodule);
		paraOA.put("sourceid", qry_meetID);
		String qry_title = (String) paraMap.get("qry_title");
		if (!StringUtil.isEmpty(qry_title)) {
			paraOA.put("taskmaintitle", qry_title);
		}
		// 如果查询条件中有 state，则进行过滤
		String qry_state = (String) paraMap.get("qry_state");
		if (qry_state != null) {
			paraOA.put("state", qry_state);
		}
		if (paraMap.containsKey("handleusercode")) {
			if (ConvertUtil.convertToInt(paraMap.get("handleusercode")) == 1) {
				paraOA.put("handleusercode", getSessionUserBean().getUser().getCode());
			}
		}
		// 传递分页信息
		Integer currentPage =  Integer.valueOf(paraMap.get("currentPage").toString());
		paraOA.put("curPageIndex", currentPage);
		Integer pageSize = Integer.valueOf(paraMap.get("pageSize").toString());
		paraOA.put("pageSize", pageSize);
		String sidx = (String) paraMap.get("sidx");
		paraOA.put("sidx", sidx);
		String sord = (String) paraMap.get("sord");
		paraOA.put("sord", sord);
		String paraOAStr = JSON.toJSONString(paraOA);
		String oaResultJson = smsWorkTasksCloseService.queryFromMeet(paraOAStr);
		OAResult<String> oaResult = JSON.parseObject(oaResultJson, OAResult.class);
		if (!oaResult.getSuccess()) {
			throw new BusinessException("查询OA系统任务列表失败，请稍后重试。");
		}
		String jsonData = oaResult.getData();
		Map<String, Object> resultData = (Map<String, Object>) JSON.parse(jsonData);
		List<Map<String, Object>> taskList = (List<Map<String, Object>>) resultData.get("dataList");
		// 日期转换
		taskList.stream().forEach(task -> {
			// 转换发起日期
			Long initiatedate = (Long) task.get("initiatedate");
			if (initiatedate != null) {
				task.put("initiatedate", new Date(initiatedate));
			}
			// 转换截止日期
			Long enddate = (Long) task.get("enddate");
			if (enddate != null) {
				task.put("enddate", new Date(enddate));
			}
		});
		/*// 根据截至时间升序，根据state升序
		taskList = taskList.stream().sorted((Map<String, Object> task1, Map<String, Object> task2) -> {
			Date enddate1 = (Date) task1.get("enddate");
			Date enddate2 = (Date) task2.get("enddate");
			if (enddate1 != null && enddate2 != null) {// 两个日期都不为空
				if (enddate1.equals(enddate2)) {
					int state1 = (int) task1.get("state");
					int state2 = (int) task2.get("state");
					return state1 - state2;
				} else {
					long betweenTime = enddate1.getTime() - enddate2.getTime();
					return betweenTime == 0 ? 0 : (betweenTime > 0 ? 1 : -1);
				}
			} else if (enddate1 == null && enddate2 == null) {// 两个日期都为空
				return 0;
			} else if (enddate1 == null) {// enddate1为空
				return 1;
			} else {
				return -1;
			}
		}).collect(Collectors.toList());
		Query query = new Query(paraMap);*/
		Integer totalCount = (Integer) resultData.get("totalCount");
		Page page = new Page(taskList, totalCount, pageSize, currentPage);
		return page;
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-22
	 * @param: paraMap
	 * @description: 创建任务
	 * @modify:
	 */
	@Override
	public void addTask(Map<String, Object> paraMap) {
		// 设置来源系统、来源模块、来源ID
		String meetId = paraMap.get("meetId").toString();
		Map<String, Object> paraOA = new HashMap<>();
		paraOA.put("sourcesys", MeetSystemConst.OATaskSourceInfo.Sourcesys);
		paraOA.put("sourcemodule", MeetSystemConst.OATaskSourceInfo.Sourcemodule);
		paraOA.put("sourceid", meetId);
		// 设置发起日期
		String initiatedate = (String) paraMap.get("initiatedate");
		if (!StringUtil.isEmpty(initiatedate)) {
			paraOA.put("initiatedate", DateUtil.stringToDate(initiatedate));
		}
		// 设置记录人信息
		String usercode = paraMap.get("usercode").toString();
		paraOA.put("usercode", usercode);
		paraOA.put("username", paraMap.get("username"));
		// 设置记录人部门信息
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(CboUserEntity.FieldCode + " = '{0}'", usercode);
		CboUserEntity cboUserEntity = cboUserService.queryObjectByWhere(sql.toString());
		CboDeptEntity cboDeptEntity = cboDeptService.queryById(String.valueOf(cboUserEntity.getDeptid()));
		paraOA.put("deptcode", cboDeptEntity.getCode());
		paraOA.put("deptname", cboDeptEntity.getName());
		// 设置记录人组织信息
		CboOrgEntity cboOrgEntity = cboOrgService.queryById(String.valueOf(cboUserEntity.getOrgid()));
		paraOA.put("orgcode", cboOrgEntity.getCode());
		paraOA.put("orgname", cboOrgEntity.getName());
		// 设置任务分类
		paraOA.put("category", paraMap.get("category"));
		// 设置办理人信息
		String handleusercode = paraMap.get("handleusercode").toString();
		paraOA.put("handleusercode", handleusercode);
		paraOA.put("handleusername", paraMap.get("handleusername"));
		// 设置发起人信息
		paraOA.put("initiatorcode", paraMap.get("initiatorcode"));
		paraOA.put("initiatorname", paraMap.get("initiatorname"));
		// 设置任务主题
		paraOA.put("taskmaintitle", paraMap.get("taskmaintitle"));
		// 设置任务内容
		paraOA.put("taskdescription", paraMap.get("taskdescription"));
		// 设置归属部门信息--办理人所在部门
		String deptid = paraMap.get("relegationdeptid").toString();
		cboDeptEntity = cboDeptService.queryById(deptid);
		paraOA.put("relegationdeptcode", cboDeptEntity.getCode());
		paraOA.put("relegationdeptname", paraMap.get("relegationdeptname"));
		// 设置归属公司信息
		sql.clear();
		sql.appendSingle(CboUserEntity.FieldCode + " = '{0}'", handleusercode);
		cboUserEntity = cboUserService.queryObjectByWhere(sql.toString());
		cboOrgEntity = cboOrgService.queryById(String.valueOf(cboUserEntity.getOrgid()));
		paraOA.put("relegationorgcode", cboOrgEntity.getCode());
		paraOA.put("relegationorgname", cboOrgEntity.getName());
		// 设置时间要求
		paraOA.put("daterequirement", paraMap.get("daterequirement"));
		// 设置截止日期
		String enddate = (String) paraMap.get("enddate");
		if (!StringUtil.isEmpty(enddate)) {
			paraOA.put("enddate", enddate);
		}
		// 设置消息是否提醒
		paraOA.put("messagesend", "1");
		String paraOAStr = JSON.toJSONString(paraOA);
		String oaResultJson = smsWorkTasksCloseService.submitFromMeet(paraOAStr);
		OAResult<String> oaResult = JSON.parseObject(oaResultJson, OAResult.class);
		if (!oaResult.getSuccess()) {
			throw new BusinessException("查询OA系统任务列表失败，请稍后重试。");
		}
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-25
	 * @param: paraMap
	 * @description: 根据条件查询用户列表
	 * @modify:
	 */
	@Override
	public List<Map<String, Object>> searchUsersByCondition(Map<String, Object> paraMap) {
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		String roleids = (String) paraMap.get("handleroleids");
		if (!StringUtil.isEmpty(roleids)) {
			resultList.addAll(baseCboUserExtendService.searchUserByRoleIds(roleids));
		}
		String deptcodes = (String) paraMap.get("handledeptcodes");
		if (!StringUtil.isEmpty(deptcodes)) {
			resultList.addAll(baseCboUserExtendService.searchUsersByDeptCodes(deptcodes));
		}
		Object teamidsObj = paraMap.get("handleteamids");
		String teamids = teamidsObj != null ? teamidsObj.toString() : "";
		if (!StringUtil.isEmpty(teamids)) {
			resultList.addAll(baseTeamUserService.searchUsersByTeams(teamids));
		}
		String handleusercodes = (String) paraMap.get("handleusercodes");
		String handleusernames = (String) paraMap.get("handleusernames");
		if (!StringUtil.isEmpty(handleusercodes)) {
			resultList.addAll(this.searchUsersByCodes(handleusercodes, handleusernames));
		}
		// 去除重复数据
		resultList = resultList.stream().distinct().collect(Collectors.toList());
		return resultList;
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-26
	 * @param: usercodes
	 * @description: 根据用户编码获取用户信息
	 * @modify:
	 */
	private List<Map<String, Object>> searchUsersByCodes(String usercodes, String usernames) {
		String[] usercodeArray = usercodes.split(",");
		String[] usernameArray = usernames.split(",");
		List<Map<String, Object>> userMapList = new ArrayList<>();
		for (int i = 0; i < usercodeArray.length; i++) {
			Map<String, Object> userMap = new HashMap<>();
			userMap.put("code", usercodeArray[i]);
			userMap.put("name", usernameArray[i]);
			userMapList.add(userMap);
		}
		return userMapList;
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-26
	 * @description: 从OA中获取编码列表
	 * @modify:
	 */
	@Override
	public Map<String, Object> searchCodeMapFromOA() {
		String oaResultJson = smsWorkTasksCloseService.createItemListFromMeet();
		OAResult<String> oaResult = JSON.parseObject(oaResultJson, OAResult.class);
		if (!oaResult.getSuccess()) {
			throw new BusinessException("查询OA系统任务列表失败，请稍后重试。");
		}
		String jsonData = oaResult.getData();
		Map<String, Object> codeMap = JSON.parseObject(jsonData, Map.class);
		return codeMap;
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-27
	 * @param: paraMap
	 * @description: 废弃任务
	 * @modify:
	 */
	@Override
	public void dropTask(Map<String, Object> paraMap) {
		String paraOAStr = JSON.toJSONString(paraMap);
		String oaResultJson = smsWorkTasksCloseService.terminateFromMeet(paraOAStr);
		OAResult<String> oaResult = JSON.parseObject(oaResultJson, OAResult.class);
		if (!oaResult.getSuccess()) {
			throw new BusinessException("作废OA系统任务列表失败，请稍后重试。");
		}
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-28
	 * @param: paraMap
	 * @description: 批量创建任务，先缓存到本地
	 * @modify:
	 */
	@Override
	public void addTaskBatch(Map<String, Object> paraMap) {
		List<Map<String, Object>> userMapList = this.searchUsersByCondition(paraMap);
		List<BasicEntity> meetTaskEntityList = new ArrayList<>();
		for (Map<String, Object> userMap : userMapList) {
			MeetTaskEntity meetTaskEntity = initMeetTaskEntity(paraMap, userMap);
			meetTaskEntityList.add(meetTaskEntity);
		}
		this.insertBatch(meetTaskEntityList);
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-28
	 * @param: meetTaskEntityList
	 * @description: 批量创建OA任务
	 * @modify:
	 */
	@Override
	public void createOATask(List<MeetTaskEntity> meetTaskEntityList) {
		StringBufferProxy sql = new StringBufferProxy();
		for (MeetTaskEntity meetTaskEntity : meetTaskEntityList) {
			Map<String, Object> paraOA = meetTaskEntity.convertToMap();
			List<Map<String, Object>> userMapList = this.searchUsersByCondition(paraOA);
			paraOA.put("sourcesys", MeetSystemConst.OATaskSourceInfo.Sourcesys);
			paraOA.put("sourcemodule", MeetSystemConst.OATaskSourceInfo.Sourcemodule);
			paraOA.put("sourceid", meetTaskEntity.getMeetid());
			// 设置消息是否提醒
			paraOA.put("messagesend", "1");
			String paraOAStr = JSON.toJSONString(paraOA);
			String oaResultJson = smsWorkTasksCloseService.submitFromMeet(paraOAStr);
			OAResult<String> oaResult = JSON.parseObject(oaResultJson, OAResult.class);
			if (oaResult.getSuccess()) {// 如果创建成功，则删除任务记录
				this.deleteById(String.valueOf(meetTaskEntity.getId()));
			}
		}
	}

	/**
	 * @Description:    根据任务发起人查询任务
	 * @Author:         mengmeng
	 * @Param:          No such property: code for class: Script1
	 * @Date:           2021/6/3 9:45
	 * @Version:        1.0
	 */
	@Override
	public Page searchTaskFromOAByUser(Map<String, Object> paraMap) {
		Map<String, Object> paraOA = new HashMap<>();
		paraOA.put("sourcesys", MeetSystemConst.OATaskSourceInfo.Sourcesys);
		paraOA.put("sourcemoudule", MeetSystemConst.OATaskSourceInfo.Sourcemodule);
//		paraOA.put("sourceid", qry_meetID);
		// 传递分页信息
		Integer currentPage = Integer.valueOf(paraMap.get("currentPage").toString());
		paraOA.put("curPageIndex", currentPage);
		Integer pageSize = Integer.valueOf(paraMap.get("pageSize").toString());
		paraOA.put("pageSize", pageSize);
		String sidx = (String) paraMap.get("sidx");
		paraOA.put("sidx", sidx + " " + (String) paraMap.get("sord") + ", id");
		String sord = "asc";
		paraOA.put("sord", sord);
		// 如果查询条件中有 state，则进行过滤
		if (paraMap.containsKey("qry_state")) {
			String qry_state = (String) paraMap.get("qry_state");
			if (!StringUtil.isEmpty(qry_state)) {
				paraOA.put("state", qry_state);
			}
		}
		if (paraMap.containsKey("usercode")) {
			String userCode = ConvertUtil.convertToString(paraMap.get("usercode"));
			if (!StringUtil.isEmpty(userCode)) {
				paraOA.put("usercode", userCode);
			}
		}
		if (paraMap.containsKey("handleusercode")) {
			String handleUserCode = ConvertUtil.convertToString(paraMap.get("handleusercode"));
			if (!StringUtil.isEmpty(handleUserCode)) {
				paraOA.put("handleusercode", handleUserCode);
			}
		}
		if (paraMap.containsKey("sourceid")) {
			String sourceId = ConvertUtil.convertToString(paraMap.get("sourceid"));
			if (!StringUtil.isEmpty(sourceId)) {
				paraOA.put("sourceid", sourceId);
			}
			else {
				// 如果没有查询到会议，传 一个不存在的会议id
				paraOA.put("sourceid", "00000000001");
			}
		}
		String paraOAStr = JSON.toJSONString(paraOA);
		String oaResultJson = smsWorkTasksCloseService.queryFromMeet(paraOAStr);
		OAResult<String> oaResult = JSON.parseObject(oaResultJson, OAResult.class);
		if (!oaResult.getSuccess()) {
			throw new BusinessException("查询OA系统任务列表失败，请稍后重试。");
		}
		String jsonData = oaResult.getData();
		Map<String, Object> resultData = (Map<String, Object>) JSON.parse(jsonData);
		List<Map<String, Object>> taskList = (List<Map<String, Object>>) resultData.get("dataList");
		if (!CollectionUtils.isEmpty(taskList)) {
			String meetNumStr = taskList.stream().map(item -> ConvertUtil.convertToString(item.get("sourceid"))).distinct().map(item -> "'" + item + "'").collect(Collectors.joining(","));
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" meetnum in (" + meetNumStr + ")");
			List<MeetManageEntity> meetManageEntityList = meetManageService.queryByWhere(sql.toString());
			Map<String, String> meetNumMap = meetManageEntityList.stream().collect(Collectors.toMap(MeetManageEntity::getMeetnum, MeetManageEntity::getName, (v1, v2) -> v1));
			// 日期转换
			taskList.stream().forEach(task -> {
				// 转换发起日期
				Long initiatedate = (Long) task.get("initiatedate");
				if (initiatedate != null) {
					task.put("initiatedate", new Date(initiatedate));
				}
				// 转换截止日期
				Long enddate = (Long) task.get("enddate");
				if (enddate != null) {
					task.put("enddate", new Date(enddate));
				}
				task.put("meetname", meetNumMap.get(ConvertUtil.convertToString(task.get("sourceid"))));
			});
		}

		Integer totalCount = (Integer) resultData.get("totalCount");
		Page page = new Page(taskList, totalCount, pageSize, currentPage);
		return page;
	}

	/**
	 * @return
	 * @author: shenyouyi
	 * @date: 2020-08-28
	 * @param: paraMap
	 * @param: userMap
	 * @description: 初始化会议任务实体类
	 * @modify:
	 */
	private MeetTaskEntity initMeetTaskEntity(Map<String, Object> paraMap, Map<String, Object> userMap) {
		MeetTaskEntity meetTaskEntity = new MeetTaskEntity();
		// 设置会议ID
		String meetId = ConvertUtil.convertToString(paraMap.get("meetId"));
		meetTaskEntity.setMeetid(Long.valueOf(meetId));
		// 设置发起日期
		String initiatedate = (String) paraMap.get("initiatedate");
		if (!StringUtil.isEmpty(initiatedate)) {
			meetTaskEntity.setInitiatedate(DateUtil.stringToDate(initiatedate));
		}
		// 设置记录人信息
		String usercode = ConvertUtil.convertToString(paraMap.get("usercode"));
		meetTaskEntity.setUsercode(usercode);
		String username = ConvertUtil.convertToString(paraMap.get("username"));
		meetTaskEntity.setUsername(username);
		// 设置记录人部门信息
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(CboUserEntity.FieldCode + " = '{0}'", usercode);
		CboUserEntity cboUserEntity = cboUserService.queryObjectByWhere(sql.toString());
		CboDeptEntity cboDeptEntity = cboDeptService.queryById(String.valueOf(cboUserEntity.getDeptid()));
		meetTaskEntity.setDeptcode(cboDeptEntity.getCode());
		meetTaskEntity.setDeptname(cboDeptEntity.getName());
		// 设置记录人组织信息
		CboOrgEntity cboOrgEntity = cboOrgService.queryById(String.valueOf(cboUserEntity.getOrgid()));
		meetTaskEntity.setOrgcode(cboOrgEntity.getCode());
		meetTaskEntity.setOrgname(cboOrgEntity.getName());
		// 设置任务分类
		meetTaskEntity.setCategory(ConvertUtil.convertToString(paraMap.get("category")));
		// 设置办理人信息
		String handleusercode = ConvertUtil.convertToString(userMap.get("code"));
		meetTaskEntity.setHandleusercode(handleusercode);
		meetTaskEntity.setHandleusername(ConvertUtil.convertToString(userMap.get("name")));
		// 设置发起人信息
		meetTaskEntity.setInitiatorcode(ConvertUtil.convertToString(paraMap.get("initiatorcode")));
		meetTaskEntity.setInitiatorname(ConvertUtil.convertToString(paraMap.get("initiatorname")));
		// 设置任务主题
		meetTaskEntity.setTaskmaintitle(ConvertUtil.convertToString(paraMap.get("taskmaintitle")));
		// 设置任务内容
		meetTaskEntity.setTaskdescription(ConvertUtil.convertToString(paraMap.get("taskdescription")));
		// 设置归属部门信息--办理人所在部门
		sql.clear();
		sql.appendSingle(CboUserEntity.FieldCode + " = '{0}'", handleusercode);
		cboUserEntity = cboUserService.queryObjectByWhere(sql.toString());
		cboDeptEntity = cboDeptService.queryById(String.valueOf(cboUserEntity.getDeptid()));
		meetTaskEntity.setRelegationdeptcode(cboDeptEntity.getCode());
		meetTaskEntity.setRelegationdeptname(cboDeptEntity.getName());
		// 设置归属公司信息
		cboOrgEntity = cboOrgService.queryById(String.valueOf(cboUserEntity.getOrgid()));
		meetTaskEntity.setRelegationorgcode(cboOrgEntity.getCode());
		meetTaskEntity.setRelegationorgname(cboOrgEntity.getName());
		// 设置时间要求
		meetTaskEntity.setDaterequirement(ConvertUtil.convertToString(paraMap.get("daterequirement")));
		// 设置截止日期
		String enddate = (String) paraMap.get("enddate");
		if (!StringUtil.isEmpty(enddate)) {
			meetTaskEntity.setEnddate(DateUtil.stringToDate(enddate));
		}
		return meetTaskEntity;
	}

}
